﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autorent.Desktop.Main;
using Autorent.Desktop.Model.AutorentMngrServiceReference;
using Autorent.Desktop.Modules.Offices.Services;
using Autorent.Desktop.Modules.Orders.Services;
using Autorent.Desktop.Modules.Reports.CompanyReports.ReportsDataSets;
using Autorent.Desktop.Modules.Reports.CompanyReports;
using Autorent.Desktop.Modules.Reports.CompanyReports.Views;

namespace Autorent.Desktop.Modules.Reports.CompanyReports.ViewModels
{
    public class CompanyMonthReportViewModel : ViewModelBase
    {
        public CompanyMonthReportViewModel(CompanyMonthReportView view, IAutoOrdersRepository ordersRepository,
            IOfficesRepository officesRepository)
        {
            this.View = view;
            View.Model = this;

            _ordersRepository = ordersRepository;
            _officesRepository = officesRepository;

            CompanyMonthReportDataSet ds = new CompanyMonthReportDataSet();
            FillCompanyMonthReportDataTable(ds);

            CompanyMonthReport report = new CompanyMonthReport();
            report.SetDataSource(ds);
            

            View.reportViewer.ViewerCore.ReportSource = report;
        }

        public CompanyMonthReportView View { get; set; }

        private readonly IAutoOrdersRepository _ordersRepository;
        private readonly IOfficesRepository _officesRepository;

        private void FillCompanyMonthReportDataTable(CompanyMonthReportDataSet ds)
        {
            decimal paymentsSum = 0;

            foreach (Office office in _officesRepository.GetOffices())
            {
                decimal officePaymentSummary = GetPaymentSum(office.AutoOrders.ToList());

                ds.CompanyMonthReportDataTable.AddCompanyMonthReportDataTableRow(
                    office.OfficeName,
                    office.Street.City.Region.Country.CountryName + ", " + office.Street.City.CityName + ", " +
                    office.Street.StreetName,
                    office.AutoOrders.Count,
                    officePaymentSummary
                    );

                paymentsSum += GetPaymentSum(office.AutoOrders.ToList());
            }
        }

        private decimal GetPaymentSum(List<AutoOrder> orders)
        {
            decimal sum = 0;

            foreach (AutoOrder order in orders)
            {
                sum += order.Payment.PaymentValue;
            }

            return sum;
        }
    }
}
